package com.attendance.chdingtask.service;

import com.attendance.chdingtask.model.AuthInfo;
import com.attendance.chdingtask.utils.dingApi.AttendanceHelper;
import com.attendance.chdingtask.utils.dingApi.UserHelper;
import com.dingtalk.api.response.OapiAttendanceGetsimplegroupsResponse;

import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DingWorkFlowService {

    private static final Logger logger= LoggerFactory.getLogger(DingWorkFlowService.class);
    @Value("${dingding.corpId}")
    String corpId;
    @Value("${dingding.reviewtoken}")
    String token;
    @Value("${dingding.receiveCallback}")
    String receiveUrl;
    @Value("${dingding.reviewAes_key}")
    String aesKey;


    /**
     * 相应钉钉回调时的值
     */
    private static final String CALLBACK_RESPONSE_SUCCESS="success";
    @Autowired
    private AuthInfoDaoService authHelper;

    @Autowired
    private UserInfoService userInfoService;
//    @Autowired
//    private DataListService dataListService;

//
//
//    public Map<String, String> receiveCallback(String signature, String timestamp, String nonce, JSONObject json) {
//        String params=" signature:" + signature + " timestamp:" + timestamp + " nonce:" + nonce + " json:" + json;
//        System.out.println("--------回调事件开始---------回调体为{}："+params);
//        String plainText =null;
//        String eventTypeName=null;
//        try {
//            DingTalkEncryptor dingTalkEncryptor=new DingTalkEncryptor(token, aesKey, corpId);
//            //从post请求的body中获取回调信息的加密数据进行解密处理
//            String encryptMsg=json.getString("encrypt");
//            plainText=dingTalkEncryptor.getDecryptMsg(signature, timestamp, nonce, encryptMsg);
//            JSONObject obj=JSON.parseObject(plainText);
//            logger.info("--------回调事件开始---------回调体为{}：",obj);
//            EventType eventType=EventType.getEventType(obj.getString("EventType"));
//            eventTypeName=eventType.name();
//            switch (eventType) {
//                case user_add_org:
////                    xtCorpUserInfoService.addUser(obj,corpId);
//                    break;
//                case user_modify_org:
////                    xtCorpUserInfoService.addUser(obj,corpId);
//                    break;
//                case attendance_check_record:
//                    dataListService.saveDataList(obj);
//                    break;
//                case check_url:
//                    logger.info("—————————————————check_url———————————————");
//                    break;
//                default:
//                    logger.error("该事件未注册处理：{}", obj);
//
//            }
////             返回success的加密信息表示回调处理成功
//            return dingTalkEncryptor.getEncryptedMap(CALLBACK_RESPONSE_SUCCESS, System.currentTimeMillis(), Utils.getRandomStr(8));
//        } catch (Exception e) {
//            System.out.println("****回调事件处理失败*******处理的数据格式为**********"+plainText+" \n **************c处理类型为***********"+eventTypeName+"\n ***************失败原因******"+e.getMessage());
//            //失败的情况，应用的开发者应该通过告警感知，并干预修复
//            logger.error("process callback failed！" + params, e);
//            return null;
//        }
//
//    }


//    public String updateCallback(String updateUrl) throws Exception {
//        String access_token=this.authHelper.getAccseToken();
//        String url="https://oapi.dingtalk.com/call_back/update_call_back?access_token=" + access_token;
//        List<String> callBackTag=new LinkedList<>();
//        callBackTag.add("org_dept_remove");
//        JSONObject args=new JSONObject();
//        args.put("call_back_tag", callBackTag);
//        args.put("token", this.token);
//        args.put("aes_key", this.aesKey);
//        args.put("url", updateUrl);
//        HttpUtil.doPostObj(url, args);
//        return updateUrl;
//    }


//    public static void main(String[] args) throws Exception {

//
//        /**
//         *   reviewtoken: scqclattendancereview
//         *   reviewAes_key: 12x29xx5lvdhntotr3x912lbytbsszyz5zx87xxxx34
//         */
//
//        DingTalkClient client=new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/register_call_back");
//        OapiCallBackRegisterCallBackRequest request=new OapiCallBackRegisterCallBackRequest();
//        request.setUrl("http://bxn.natapp1.cc/api/sccallback/reciveInstanceCallback");
//        request.setAesKey("12x29xx5lvdhntotr3x912lbytbsszyz5zx87xxxx34");
//        request.setToken("scqclattendancereview");
//        request.setCallBackTag(Arrays.asList("user_add_org", "user_modify_org","attendance_check_record","attendance_overtime_duration","attendance_schedule_change","bpms_task_change","bpms_instance_change"));
//        OapiCallBackRegisterCallBackResponse response=client.execute(request, "97b79474e0d33e91abf93c5b10c17640");
//
//        System.out.println(response.getErrmsg());

//        DingTalkClient  client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/update_call_back");
//        OapiCallBackUpdateCallBackRequest request = new OapiCallBackUpdateCallBackRequest();
//        request.setUrl("http://110.249.164.50:8092/api/callback/reciveInstanceCallback");
//        request.setAesKey("12x29xx5lvdhntotr3x9qhlbytb18zyz5zx87xxxx34");
//        request.setToken("xtnypostiontask");
//        request.setCallBackTag(Arrays.asList("user_add_org", "user_modify_org"));
//        OapiCallBackUpdateCallBackResponse response = client.execute(request,"b65562f8412331928611fce99aa80735");


//        DingTalkClient  client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/update_call_back");
//        OapiCallBackUpdateCallBackRequest request = new OapiCallBackUpdateCallBackRequest();
//        request.setUrl("http://bxn.natapp1.cc/api/callback/reciveInstanceCallback");
//        request.setAesKey("12x29xx5lvdhntotr3x9qhlbytb18zyz5zx87xxxx34");
//        request.setToken("xtnypostiontask");
//        // 注册事件
//        /**
//         * "user_add_org", "user_modify_org", "user_leave_org", "org_dept_create", "org_dept_modify", "org_dept_remove", "bpms_task_change", "bpms_instance_change"
//         */
//        request.setCallBackTag(Arrays.asList("user_add_org", "user_modify_org"));
//        OapiCallBackUpdateCallBackResponse response = client.execute(request,"260b4a32a6c832bd8e8f0ec652eadf71");
//        System.out.println(response.getCode());

//        DingTalkClient client1=new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/get_call_back");
//        OapiCallBackGetCallBackRequest request1=new OapiCallBackGetCallBackRequest();
//        request1.setHttpMethod("GET");
//        OapiCallBackGetCallBackResponse response1=client1.execute(request1, "97b79474e0d33e91abf93c5b10c17640");
//        System.out.println(response1.getCallBackTag());
//        System.out.println(response1.getUrl());


//    }

//
//
//    public String getReviewUrl() throws ApiException, OApiException {
//        String accessToken=this.authHelper.getAccessTokenByCorpId("ding28d1a5d227c02b4835c2f4657eb6378f");
//        DingTalkClient  client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/get_call_back");
//        OapiCallBackGetCallBackRequest request = new OapiCallBackGetCallBackRequest();
//        request.setHttpMethod("GET");
//        OapiCallBackGetCallBackResponse response = client.execute(request,accessToken);
//        if(!response.isSuccess()){
//            return response.getErrmsg();
//        }
//        System.out.println(response.getUrl());
//        return response.getUrl();
//    }

//    public Result updateReviewUrl(String url) throws OApiException, ApiException {
//        String accessToken=this.authHelper.getAccessTokenByCorpId("ding28d1a5d227c02b4835c2f4657eb6378f");
//        DingTalkClient client=new DefaultDingTalkClient("https>//oapi.dingtalk.com/call_back/update_call_back");
//        OapiCallBackUpdateCallBackRequest request=new OapiCallBackUpdateCallBackRequest();
//        request.setAesKey("xtnypostiontask");
//        request.setToken("12x29xx5lvdhntotr3x9qhlbytb18zyz5zx87xxxx34");
//        request.setUrl(url);
//        request.setCallBackTag(Arrays.asList("user_add_org","user_modify_org","user_leave_org"));
//        OapiCallBackUpdateCallBackResponse response=client.execute(request,accessToken);
//        if(!response.isSuccess()){
//            return Result.error(response.getErrmsg());
//        }
//        return Result.success(response.isSuccess());
//    }


    public void startUpdateUserInfo(String deptId) throws Exception {
        AuthInfo authInfo=authHelper.findById(1L);
        if(null == authInfo){
            return;
        }
        String accessToken=this.authHelper.getAccessToken(authInfo);
        OapiUserListidResponse.ListUserByDeptResponse userByDeptResponse=UserHelper.getUserIdLists(accessToken,Long.valueOf(deptId));
        List<String> useridList=userByDeptResponse.getUseridList();
        if(null != useridList&& useridList.size()>0){
            userInfoService.saveListUser(useridList,authInfo.getCorpId(),accessToken);
        }

    }


}
